package com.snow.useviewdemo;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.snow.useviewdemo.adapter.NAdapter;
import com.snow.useviewdemo.animation.OPTFirstActivity;
import com.snow.useviewdemo.bean.MainListBean;
import com.snow.useviewdemo.function.AlgorithmTestActivity;
import com.snow.useviewdemo.function.AndroidNativeShareActivity;
import com.snow.useviewdemo.function.CustomViewEffectTestActivity;
import com.snow.useviewdemo.function.DownLoadTestActivity;
import com.snow.useviewdemo.function.LaunchVideoWebViewActivity;
import com.snow.useviewdemo.function.PermissionTestActivity;
import com.snow.useviewdemo.function.RecyclerViewTestActivity;
import com.snow.useviewdemo.function.TestSurfaceViewActivity;
import com.snow.useviewdemo.function.audio.AudioTestActivity;
import com.snow.useviewdemo.function.blur.BlurActivity;
import com.snow.useviewdemo.function.calendar.CalendarCustomActivity;
import com.snow.useviewdemo.function.calendartwo.NCalendarTestActivity;
import com.snow.useviewdemo.function.chat.ChatActivity;
import com.snow.useviewdemo.function.copy.CopyTestAct;
import com.snow.useviewdemo.function.eventtouch.EventDeliveryActivity;
import com.snow.useviewdemo.function.loading.LoadingViewTestActivity;
import com.snow.useviewdemo.function.navigation.NavigationBarActivity;
import com.snow.useviewdemo.function.phonesystem.PhoneAppsActivity;
import com.snow.useviewdemo.function.phonesystem.PhoneSystemParamsActivity;
import com.snow.useviewdemo.function.shadow.ShadowTestActivity;
import com.snow.useviewdemo.function.suspension.AppBarCoordiActivity;
import com.snow.useviewdemo.function.suspension.SuspensionActivity;
import com.snow.useviewdemo.function.systems.GetTopRuningActivity;
import com.snow.useviewdemo.function.systems.SkipToAppSetingActivity;
import com.snow.useviewdemo.function.transition.TransitionRootTestActivity;
import com.snow.useviewdemo.function.wallpaper.WallpagerSettingActivity;
import com.snow.useviewdemo.function2.camera.CameraXActivity;
import com.snow.useviewdemo.function2.constraint.ConstraintLayoutTestActivity;
import com.snow.useviewdemo.function2.darkmode.DarkModeTestActivity;
import com.snow.useviewdemo.function2.deviceid.ObtailDeviceIdActivity;
import com.snow.useviewdemo.function2.exposure.ExposureViewTestActivity;
import com.snow.useviewdemo.function2.flowlayout.FlowLayoutTestActivity;
import com.snow.useviewdemo.function2.gyroscope.GyroscopeTestActivity;
import com.snow.useviewdemo.function2.hindicon.HindDeskAppIconActivity;
import com.snow.useviewdemo.function2.notice.ResidentNoticeTestActivity;
import com.snow.useviewdemo.function2.other.PreferencesDatastoreActivity;
import com.snow.useviewdemo.function2.printer.PrinterSettingActivity;
import com.snow.useviewdemo.function2.radius.RadiusViewTestActivity;
import com.snow.useviewdemo.function2.refreshtwo.SmartRefreshTwoActivity;
import com.snow.useviewdemo.function2.service.CheckOServiceActivity;
import com.snow.useviewdemo.function2.spannable.TestTextExportPackUpActivity;
import com.snow.useviewdemo.function2.statusbar.StatusBarStyleActivity;
import com.snow.useviewdemo.function2.viewfliper.UPMarqueeActivity;
import com.snow.useviewdemo.function2.wait.CountDownLatchTestAct;
import com.snow.useviewdemo.glide.GlidePicActivity;
import com.snow.useviewdemo.glide.ImageViewShowActivity;
import com.snow.useviewdemo.html.HtmlWebViewShowAct;
import com.snow.useviewdemo.html.TestHtmlDataShowAct;
import com.snow.useviewdemo.html.WebViewH5VideoAct;
import com.snow.useviewdemo.kotlin.User;
import com.snow.useviewdemo.longpicture.LoadLongPngAct;
import com.snow.useviewdemo.longpicture.LoadLongPngScrollViewImgAct;
import com.snow.useviewdemo.longpicture.LongPngWrapContentAct;
import com.snow.useviewdemo.lottie.LottieAct;
import com.snow.useviewdemo.num.NUMScaleActivity;
import com.snow.useviewdemo.play.PlayMainActivity;
import com.snow.useviewdemo.qiniuplay.PlayTextureViewAct;
import com.snow.useviewdemo.qiniuplay.QPLFullPlayVideoAct;
import com.snow.useviewdemo.screenlock.ScreenLockActivity;
import com.snow.useviewdemo.test.rxjava.RxJavaTestActivity;
import com.snow.useviewdemo.util.HandlerHelper;
import com.snow.useviewdemo.util.LogUtils;
import com.snow.useviewdemo.util.RetryTimesFunction;
import com.snow.useviewdemo.util.UAppUtils;
import com.snow.useviewdemo.viewpager2.NewsActivty;
import com.snow.useviewdemo.zoomimage.ZoomImageAct;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    NAdapter nAdapter;
    @BindView(R.id.editText)
    EditText editText;
    private List<MainListBean> itemList;
    private List<MainListBean> itemTempList;
    long time01;
    long time02;
    public static Context mainContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        itemList = new ArrayList<>();
        itemTempList = new ArrayList<>();
        mainContext = this;
        recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        nAdapter = new NAdapter<MainListBean>(this, R.layout.adapter_main_item, onItemClickListener) {
            @Override
            public void onBindViewHolder(NViewHolder holder, MainListBean bean, int position) {
                TextView viewById = holder.itemView.findViewById(R.id.btn_item);
                viewById.setText(bean.getName());
            }
        };
        recyclerView.setAdapter(nAdapter);
        addData();
        initListener();
        time01 = System.currentTimeMillis();
        time02 = SystemClock.uptimeMillis();
        long time03 = SystemClock.currentThreadTimeMillis();
        long time04 = SystemClock.elapsedRealtime();
        long time05 = SystemClock.elapsedRealtimeNanos();
        Log.e("snow_time", "=====time01=======" + time01);
        Log.e("snow_time", "=====time02=======" + time02);
        Log.e("snow_time", "=====time03=======" + time03);
        Log.e("snow_time", "=====time04=======" + time04);
        Log.e("snow_time", "=====time05=======" + time05);

        HandlerHelper.post(() -> {
            Log.e("snow_handler", "=====post=======");
        });
        HandlerHelper.postDelay(() -> {
            Log.e("snow_handler", "=====postDelay====5秒===");
        }, 5000);
        HandlerHelper.postDelay(() -> {
            Log.e("snow_handler", "=====postDelay====10秒===");
        }, 10000);
        //这种操作崩溃，报空指针
//        List<String> liddd = new ArrayList<>();
//        List<String> ddd = null;
//        liddd.addAll(ddd);
//        //测试直接跳转
//        startActivity(new Intent(this, WebViewH5VideoAct.class));
//        finish();
//        testObservableRetry();
    }

    private void initListener() {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchNotify(s.toString());
            }
        });
    }

    NAdapter.OnItemClickListener<MainListBean> onItemClickListener = new NAdapter.OnItemClickListener<MainListBean>() {
        @Override
        public void onItemClick(View itemView, MainListBean bean, int position) {
            startActivity(new Intent(MainActivity.this, bean.getaClass()));
            Log.e("snow_time", "=====dianji==position:" + position + "==class===" + bean.getaClass().getSimpleName());
            Log.e("snow_time", "=====dianji=======" + (SystemClock.uptimeMillis() - time02) / 1000);
        }
    };

    private void addData() {
        itemList.add(new MainListBean("测试", TestActivity.class));
        itemList.add(new MainListBean("下载测试", DownLoadTestActivity.class));
        itemList.add(new MainListBean("测试通知", ResidentNoticeTestActivity.class));
        itemList.add(new MainListBean("overridePendingTransition测试", OPTFirstActivity.class));
        itemList.add(new MainListBean("CameraX拍照Test", CameraXActivity.class));
        itemList.add(new MainListBean("Preferences Datastore Test", PreferencesDatastoreActivity.class));
        itemList.add(new MainListBean("类似打印机打印汉字(数字滚动)", PrintActivity.class));
//        itemList.add(new MainListBean("跳转Two", TextMoveActivity.class));
//        itemList.add(new MainListBean("跳转Three", LyricTestActivity.class));
        itemList.add(new MainListBean("跳转圆形图表", FormTwoActivity.class));
        itemList.add(new MainListBean("跳转圆形图表", FormTwoActivity.class));
        itemList.add(new MainListBean("跳转横向累加图标", FormOneActivity.class));
        itemList.add(new MainListBean("跳转播放器", QPLFullPlayVideoAct.class));
        itemList.add(new MainListBean("跳转PLTextureView播放器", PlayTextureViewAct.class));
        itemList.add(new MainListBean("TextView长按复制测试", CopyTestAct.class));
        itemList.add(new MainListBean("ImageView缩放", ZoomImageAct.class));
        itemList.add(new MainListBean("测试Html数据加载显示", TestHtmlDataShowAct.class));
        itemList.add(new MainListBean("测试HtmlWebview加载显示", HtmlWebViewShowAct.class));
        itemList.add(new MainListBean("测试Webview加载h5含视频(全屏)", WebViewH5VideoAct.class));
        itemList.add(new MainListBean("播放器管理类测试", PlayMainActivity.class));
        itemList.add(new MainListBean("长图加载测试", LoadLongPngAct.class));
        itemList.add(new MainListBean("长图加载测试2", LongPngWrapContentAct.class));
        itemList.add(new MainListBean("长图加载测试3", LoadLongPngScrollViewImgAct.class));
        itemList.add(new MainListBean("数字滚动和倒计时=点击虚拟键盘空白处消失", NUMScaleActivity.class));
        itemList.add(new MainListBean("LottieAct动画", LottieAct.class));
        itemList.add(new MainListBean("Glide图片封装加载", GlidePicActivity.class));
        itemList.add(new MainListBean("类似新闻功能", NewsActivty.class));
        itemList.add(new MainListBean("锁屏的测试", ScreenLockActivity.class));
        itemList.add(new MainListBean("权限测试页面", PermissionTestActivity.class));
        itemList.add(new MainListBean("SurfaceView测试", TestSurfaceViewActivity.class));
        itemList.add(new MainListBean("RecyclerView测试", RecyclerViewTestActivity.class));
        itemList.add(new MainListBean("多声音重叠（第三方播放）测试", AudioTestActivity.class));
        itemList.add(new MainListBean("测试跟h5有关的本地加载", LaunchVideoWebViewActivity.class));
        itemList.add(new MainListBean("调用系统分享文件（其他应用打开文件）", AndroidNativeShareActivity.class));
        itemList.add(new MainListBean("仿微信聊天页面", ChatActivity.class));
        itemList.add(new MainListBean("算法测试类", AlgorithmTestActivity.class));
        itemList.add(new MainListBean("自定义可左右滑动的日历", CalendarCustomActivity.class));
        itemList.add(new MainListBean("NCalendar日历依赖库", NCalendarTestActivity.class));
        itemList.add(new MainListBean("手机系统相关参数输出", PhoneSystemParamsActivity.class));
        itemList.add(new MainListBean("测试正在加载的view", LoadingViewTestActivity.class));
        itemList.add(new MainListBean("测试布局阴影", ShadowTestActivity.class));
        itemList.add(new MainListBean("自定义view显示效果", CustomViewEffectTestActivity.class));
        itemList.add(new MainListBean("滑动悬浮tab功能实现", SuspensionActivity.class));
        itemList.add(new MainListBean("AppbarLayout折叠效果", AppBarCoordiActivity.class));
        itemList.add(new MainListBean("图片的高斯模糊效果", BlurActivity.class));
        itemList.add(new MainListBean("获取运行前台的Activity及应用包名", GetTopRuningActivity.class));
        itemList.add(new MainListBean("垂直滚动消息效果", UPMarqueeActivity.class));
        itemList.add(new MainListBean("导航栏效果", NavigationBarActivity.class));
        itemList.add(new MainListBean("图片加载的各种样式", ImageViewShowActivity.class));
        itemList.add(new MainListBean("状态栏和内容的几种样式", StatusBarStyleActivity.class));
        itemList.add(new MainListBean("获取手机唯一标识及相关信息", ObtailDeviceIdActivity.class));
        itemList.add(new MainListBean("跳转手机设置的各种页面", SkipToAppSetingActivity.class));
        itemList.add(new MainListBean("获取手机安装所有应用的信息", PhoneAppsActivity.class));
        itemList.add(new MainListBean("验证8.0以后启动service的问题", CheckOServiceActivity.class));
//        itemList.add(new MainListBean("文字转语音", WordChangeAudioActivity.class));
        itemList.add(new MainListBean("陀螺仪使用预览图片", GyroscopeTestActivity.class));
        itemList.add(new MainListBean("研究View是否在屏幕中显示", ExposureViewTestActivity.class));
        itemList.add(new MainListBean("研究深色模式", DarkModeTestActivity.class));
        itemList.add(new MainListBean("约束布局使用示例", ConstraintLayoutTestActivity.class));
        itemList.add(new MainListBean("设置壁纸保活", WallpagerSettingActivity.class));
        itemList.add(new MainListBean("流式布局实现示例", FlowLayoutTestActivity.class));
        itemList.add(new MainListBean("文字收起展开", TestTextExportPackUpActivity.class));
        itemList.add(new MainListBean("打印机的效果", PrinterSettingActivity.class));
        itemList.add(new MainListBean("测试圆角控件", RadiusViewTestActivity.class));
        itemList.add(new MainListBean("Activity转场动画", TransitionRootTestActivity.class));
        itemList.add(new MainListBean("测试等待所有完成在执行", CountDownLatchTestAct.class));
        itemList.add(new MainListBean("RxJavaTestActivity", RxJavaTestActivity.class));
        itemList.add(new MainListBean("EventDeliveryActivity", EventDeliveryActivity.class));
        itemList.add(new MainListBean("SmartRefreshLayout实现淘宝二楼", SmartRefreshTwoActivity.class));
        itemList.add(new MainListBean("隐藏应用图标", HindDeskAppIconActivity.class));
        nAdapter.replaceData(itemList);
        String appSign = UAppUtils.init().getAppSign(APPApplication.getInstance());
        LogUtils.e("appSign====" + appSign);
    }

    private void searchNotify(String key) {
        itemTempList.clear();
        if (TextUtils.isEmpty(key)) {
            itemTempList.addAll(itemList);
        } else {
            for (int i = 0; i < itemList.size(); i++) {
                MainListBean bean = itemList.get(i);
                if (!TextUtils.isEmpty(bean.getName()) && bean.getName().contains(key)) {
                    itemTempList.add(bean);
                }
            }
        }
        nAdapter.replaceData(itemTempList);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        UAppUtils.gotoHomeActivity(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }


    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.e("PlayMainActivity=====onResume");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private int timess = 0;

    /**
     * 测试rx的重试
     */
    private void testObservableRetry() {
        Observable.unsafeCreate(new ObservableSource<List<User>>() {

            @Override
            public void subscribe(@NotNull Observer<? super List<User>> observer) {
                try {
                    LogUtils.d("test subscribe timess：" + timess);
                    if (timess > 2) {// 检查请求返回，是否发生token失效情况
                        observer.onNext(new ArrayList<User>());
                    } else {// token失效
                        observer.onError(new Exception("token is invalid"));
                    }
                    timess++;
                } catch (Exception e) {
                    observer.onError(e);
                }
            }
        })
                .retryWhen(new RetryTimesFunction(5, 3000)) // onError发生时，retryWhen操作符会触发处理，这里的1表示最大重试次数，3000表示延时请求时间
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<User>>() {
                    @Override
                    public void accept(List<User> users) throws Exception {
                        LogUtils.d("test success");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.d("test fail");
                    }
                });
    }

}
